const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { validatePagination } = require('../utils/validation');

// 获取字体列表
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      search,
      populate 
    } = req.query;
    
    // 验证分页参数
    const { error } = validatePagination({ page: parseInt(page), pageSize: parseInt(pageSize) });
    if (error) {
      return res.status(400).json({ error: error.details[0].message });
    }
    
    // 确保参数为有效数字
    const pageNum = Math.max(1, parseInt(page) || 1);
    const pageSizeNum = Math.max(1, parseInt(pageSize) || 20);
    const offset = (pageNum - 1) * pageSizeNum;
    
    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params = [];
    
    if (search) {
      whereClause += ' AND (f.name LIKE ? OR f.font_family LIKE ?)';
      params.push(`%${search}%`, `%${search}%`);
    }
    
    // 查询总数
    const [countResult] = await db.query(
      `SELECT COUNT(*) as total FROM fonts f ${whereClause}`,
      params
    );
    const total = countResult[0].total;
    
    // 查询数据
    const query = `
      SELECT 
        f.id,
        f.name,
        f.font_family,
        f.font_url,
        f.preview_text,
        f.type,
        f.created_at,
        f.updated_at
      FROM fonts f
      ${whereClause}
      ORDER BY f.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await db.query(query, [...params, pageSizeNum, offset]);
    
    // 格式化数据
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        font_family: row.font_family,
        font_url: row.font_url,
        preview_text: row.preview_text,
        type: row.type,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && {
          file: {
            data: {
              id: row.id,
              attributes: {
                url: row.font_url
              }
            }
          },
          img: {
            data: {
              id: row.id,
              attributes: {
                url: row.preview_text
              }
            }
          }
        })
      }
    }));
    
    res.json({
      data,
      meta: {
        pagination: {
          page: pageNum,
          pageSize: pageSizeNum,
          pageCount: Math.ceil(total / pageSizeNum),
          total
        }
      }
    });
  } catch (error) {
    console.error('获取字体列表失败:', error);
    res.status(500).json({ error: '获取字体列表失败' });
  }
});

module.exports = router;